<?php

namespace app\admin\controller;

use think\Controller;
use think\Session;
use think\Cookie;
use think\Db;
use think\Request;

class User extends Controller
{
    public $add;
    public $check;
    public $del;
    public $update;
    public function __construct()
    {
        parent::__construct();
        $power = $this->checkPower('管理员');
        if(empty($power)){
            $this->add = 0;
            $this->check =0;
            $this->update =0;
            $this->del =0;
        }else{
            $this->add = $power[0]['padd'];
            $this->check = $power[0]['pcheck'];
            $this->update = $power[0]['pupdate'];
            $this->del = $power[0]['pdel'];
        }
        
    }
    // 渲染登录页面
    public function index()
    {
        return $this->fetch('login');
    }

    // 执行登录
    public function doLogin()
    {
        $user_name = input('post.userName');
        $password = md5(input('post.password'));
        $code = input('post.code');

        if ($user_name === '') {
            return json(['msg' => '用户名不能为空！', 'code' => 1]);
        }
        if ($password === '') {
            return json(['msg' => '密码不能为空！', 'code' => 1]);
        }
        if ($code === '') {
            return json(['msg' => '验证码不能为空！', 'code' => 1]);
        }
        if (!captcha_check($code)) {
            //验证失败 
            return json(['msg' => '验证码错误!', 'code' => 1]);
        } else {
            $admin = Db::name('admin')->field('id,user,pwd')->where('user', $user_name)->find();
            if (empty($admin)) {
                return json(['msg' => '用户不存在！', 'code' => 1]);
            }
            if ($password !== $admin['pwd']) {
                return json(['msg' => '密码错误！', 'code' => 1]);
            }

            $time = time();
            Db::name('admin')->where('user', $user_name)->update(['last_login_time' => $time]);
            // 登录成功 将用户名存到cookies
            // 设置Cookie 有效期为 3600秒 
            Cookie::set('userName', $user_name, 3600);
            Cookie::set('isLogin', 1, 3600);
            Cookie::set('id', $admin['id'], 3600);
            return json(['msg' => '登录成功！', 'code' => 0]);
        }
    }

    // 退出
    public function logout()
    {
        $user_name = Cookie::get('userName');
        $time = time();
        Db::name('admin')->where('user', $user_name)->update(['last_logout_time' => $time]);
        Cookie::delete('userName');
        Cookie('isLogin', 0);
        $this->success('退出成功!', 'admin/User/index');
    }

    // 查看权限
    public function checkPower($type){
        $pid = Cookie::get('id');
        $power = Db::name('power')->field('padd,pdel,pcheck,pupdate')->where('pname', $type)->where('aid',$pid)->select();
        
        return $power;
    }

    // 渲染用户资料页面
    public function userInfo()
    {
        $user_name = Cookie::get('userName');
        $id = Cookie::get('id');
        $data = [
            'user' => $user_name,
            'id' => $id,
        ];
        $this->assign('data', $data);
        return $this->fetch('userInfo');
    }

    // 提交用户资料
    public function changeInfo()
    {
        $info = input('post.');
        $user_id = $info['user_id'];
        $in = Db::name('user_info')->where('user_id', $user_id)->find();
        if (empty($in)) {
            $res = Db::name('user_info')->insert($info);
        } else {
            $res = Db::name('user_info')->where('user_id', $user_id)->update($info);
        }

        if ($res) {
            return json(['code' => 0, 'msg' => '提交成功！']);
        } else {
            return json(['code' => 1, 'msg' => '提交失败！']);
        }
    }

    // 渲染修改密码页面
    public function showChangePwd()
    {
        $admin = Cookie::get('userName');
        $info = Db::name('admin')->field('user,pwd')->where('user', $admin)->find();

        $data = [
            'old' => $info['pwd'],
            'user' => $info['user'],
        ];
        $this->assign('old', $data);
        return $this->fetch('changePwd');
    }

    // 修改密码
    public function changePwd()
    {
        $old_pwd = input('post.oldPwd');
        $new_pwd = input('post.newPwd');
        $conf_pwd = input('post.confPwd');

        if (empty($old_pwd)) {
            return json(['msg' => '请输入旧密码！', 'code' => 1]);
        }
        if (empty($new_pwd)) {
            return json(['msg' => '新密码不能为空！', 'code' => 1]);
        }
        if (empty($conf_pwd)) {
            return json(['msg' => '请输入确认密码！', 'code' => 1]);
        }
        if ($conf_pwd != $new_pwd) {
            return json(['msg' => '确认密码与新密码不一致！', 'code' => 1]);
        }

        $admin = Cookie::get('userName');
        $pwd = Db::name('admin')->field('pwd')->where('user', $admin)->find();
        if ($old_pwd != $pwd['pwd']) {
            return json(['msg' => '输入的旧密码与原密码不一致！', 'code' => 1]);
        }

        $res = Db::name('admin')->field('pwd')->where('user', $admin)->update(['pwd' => $new_pwd]);
        if ($res) {
            return json(['msg' => '修改密码成功！', 'code' => 0]);
        } else {
            return json(['msg' => '未知错误！', 'code' => 1]);
        }
    }

    // 渲染用户中心页面
    public function showUserList()
    {
        return $this->fetch('userList');
    }

    // 用户信息
    public function userList($key = '')
    {
        if ($key == '') {
            $info = Db::name('admin')->alias('ad')->join('user_info info', 'ad.id = info.user_id')->field('ad.id, ad.last_login_time, ad.user, info.userEmail, info.sex, info.img')->select();
            $count = count($info);
        } else {
            $info = Db::name('admin')->alias('ad')->join('user_info info', 'ad.id = info.user_id')->field('ad.id, ad.last_login_time, ad.user, info.userEmail, info.sex, info.img')->where('ad.user', 'like', "%{$key}%")->select();
            $count = count($info);
        }
        // dump($info);
        if ($info) {
            return json([
                'count' => $count,
                'code' => 0,
                'msg' => '',
                'data' => $info,
            ]);
        }
    }

    //渲染添加用户页面
    public function showUserAdd()
    {
        return $this->fetch('userAdd');
    }

    // 添加用户或编辑用户信息
    public function userAdd()
    {
        $user = rtrim(input('post.user'));
        $sex = input('post.sex');
        $userEmail = input('post.userEmail');
        $pwd = input('post.pwd');
        $id = input('post.id');

        if (empty($id)) { //没有ID就 插入
            if($this->add != 1){
                return json(['code' => 3, 'msg' => '您没有这权限！']);
            }

            $insert_res = Db::name('admin')->insert(['user' => $user, 'pwd' => $pwd]);
            if (!$insert_res) {
                return json(['code' => 1, 'msg' => '添加失败！']);
            }
            $new_id = Db::name('admin')->getLastInsId();

            $info_res = Db::name('user_info')->insert(['sex' => $sex, 'userEmail' => $userEmail, 'user_id' => $new_id]);
            if ($info_res) {
                return json(['code' => 0, 'msg' => '添加成功！']);
            } else {
                return json(['code' => 1, 'msg' => '添加失败！']);
            }
        } else { //有id 就更新

            if($this->update != 1){
                return json(['code' => 3, 'msg' => '您没有这权限！']);
            }
            $update_res = Db::name('admin')->alias('ad')->join('user_info in', 'ad.id = in.user_id')->where('ad.id', $id)->update(['ad.user' => $user, 'ad.pwd' => $pwd, 'in.sex' => $sex, 'in.userEmail' => $userEmail]);

            if ($update_res) {
                return json(['code' => 0, 'msg' => '操作成功！']);
            } else {
                return json(['code' => 1, 'msg' => '操作失败！']);
            }
        }
    }

    //删除用户
    public function userDel($id)
    {
        if($this->del != 1){
            return json(['code' => 3, 'msg' => '您没有这权限！']);
        }

        $res = Db::name('admin')->where('id', 'in', $id)->delete();
        if (!$res) {
            return json(['msg' => '删除失败', 'code' => 1]);
        }
        $info = Db::name('user_info')->where('user_id', 'in', $id)->delete();
        if ($info) {
            return json(['msg' => '删除成功！', 'code' => 0]);
        } else {
            return json(['msg' => '删除失败！', 'code' => 1]);
        }
    }

    //搜索用户
    public function search($key)
    {
        return $this->userList($key);
    }

    // 渲染权限管理页面
    public function showRbac()
    {
        $admin = Cookie::get('userName');
        $data = ['admin' => $admin];
        $this->assign('rbac', $data);
        return $this->fetch('showRbac');
    }

    // 返回权限管理信息
    public function rbac($key = '')
    {
        if (empty($key)) {
            $info = Db::name('power')->alias('p')->join('admin a', 'p.aid = a.id')->field('p.pid,p.pname,p.padd,p.pdel,p.pcheck,p.pupdate,a.user')->select();
            $count = count($info);
        } else {
            $info = Db::name('power')->alias('p')->join('admin a', 'p.aid = a.id')->field('p.pid,p.pname,p.padd,p.pdel,p.pcheck,p.pupdate,a.user')->where('p.pname|a.user', 'like', "%{$key}%")->select();
            $count = count($info);
        }

        return json([
            'count' => $count,
            'code' => 0,
            'msg' => '',
            'data' => $info,
        ]);
    }

    // 进行更改权限
    public function changePower($field, $on, $pid)
    {
        if($this->update != 1){
            return json(['code' => 3, 'msg' => '您没有这权限！']);
        }

        if ($on == 'false') {
            $on = 0;
        } elseif ($on == 'true') {
            $on = 1;
        }

        $res = Db::name('power')->where('pid', $pid)->update([$field => $on]);
        if ($res) {
            return json(['msg' => '修改成功！', 'code' => 0]);
        } else {
            return json(['msg' => '修改失败！', 'code' => 1]);
        }
    }

    // 删除权限
    public function del($id, $user)
    {
        if($this->del != 1){
            return json(['code' => 3, 'msg' => '您没有这权限！']);
        }

        if (is_array($user)) {
            if (in_array('admin', $user)) {
                return json(['msg' => '您的选择包含admin超级管理员，您没有权利删除该用户，请重新选择！', 'code' => 1]);
            }
        }
        if($user == 'admin'){
            return json(['msg' => '您的选择包含admin超级管理员，您没有权利删除该用户，请重新选择！', 'code' => 1]);
        }

        $res = Db::name('power')->where('pid', $id)->delete();
        if ($res) {
            return json(['msg' => '删除成功！', 'code' => 0]);
        } else {
            return json(['msg' => '删除失败！', 'code' => 1]);
        }
    }

    // 渲染addPower
    public function addPower(){
        $admin = Db::name('admin')->field('id,user')->select();
        $power = ['新闻','案例','图片','管理员','轮播图','公司历史','合作伙伴','团队列表','公司配置'];
        $data = [
            'admin' => $admin,
            'power' => $power,
        ];
        $this->assign('rbac', $data);
        return $this->fetch('addPower');
    }

    // 添加管理员的权限
    public function powerAdd(){
        if($this->add != 1){
            return json(['code' => 3, 'msg' => '您没有这权限！']);
        }

        $info = input('post.');
        $res = Db::name('power')->insert($info);
        if($res){
            return json(['msg'=>'添加成功!','code'=>0]);
        }else{
            return json(['msg'=>'添加失败!','code'=>1]);
        }
    }
}
